#coding:utf8
#
# Author: CMGS
# Created on 2010-9-15
#
from common import config as _config
from common import defcode as _defcode
from common import defevent as _defevent
from libs.event import ec as _ec
from libs.rpc import rpc as _rpc
from libs.debugger import Debugger as _debugger
from libs.session import sessionPool as _sessionPool
from appcontrol.apicontrol import add as _add

class Modify(object):
    
    def update(self, fileHash, sid, data):
        _debugger.out('callback for %s' % fileHash)
        sessions = _sessionPool.getSessions(fileHash)
        
        if sessions is None or not sessions.has_key(sid):
            return _rpc.toJson({'code': _defcode.OPT_FAILED, 'reason': 'no session'})

        if not _add(sessions, data):
            return _rpc.toJson({'code': _defcode.OPT_FAILED, 'reason': 'invaild json'})

        for sid in sessions.keys():
            if sid in _config.UNSID_KEY:
                continue
            if sessions[sid].has_key(_config.CLIENT_PUSHED) and (sessions[sid].has_key(_config.CLIENT_READED) and sessions[sid][_config.CLIENT_READED]):
                sessions[sid][_config.CLIENT_PUSHED] = len(sessions[_config.MEM_MODIFIES_NAME]) - 1
                sessions[sid][_config.CLIENT_READED] = False
            _ec.dispatch(_defevent.API_FILE_MODIFY, hash = fileHash, sid = sid)

        return _rpc.toJson({'code': _defcode.OPT_OK})

modify = Modify()
update = modify.update
